from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import User
import re
from user.searializers import Addrser
from user.models import Addr

# Create your views here.
class CheckUsername(APIView):
    def get(self,request,username):
        # 判断用户名格式
        if not re.findall(r'^[a-zA-Z]\w{4,15}$',username):
            # 要求字母开头，中间为数字字母下划线，长度是5-16
            return Response({'code':404,'msg':'用户名格式不正确'})
        # 判断用户是否存在 get filter
        if User.objects.filter(username=username):
            return  Response({'code':400,'msg':'用户名重复'})
        else:
            return Response({'code':200,'msg':'ok'})

class CheckMobile(APIView):
    def get(self,request,mobile):
        # 判断手机号格式是否满足要求
        if not re.findall(r'^1[3-9]\d{9}$',mobile):
            return Response({'code':404,'msg':'手机号格式不正确'})

#         判断手机号是否存在
        if User.objects.filter(mobile=mobile):
            return Response({'code':400,'msg':'手机号重复'})
        else:
            return Response({'code':200,'msg':'ok'})


import random,string,redis
from captcha.image import ImageCaptcha
from django.http import HttpResponse
class ImgCode(APIView):
    def get(self,request,uuid):
        # 1.生成4位验证码
        code = ''.join(random.sample(string.ascii_letters + string.digits,4))
        print(code)
#         生成图形验证码
        cap = ImageCaptcha()  # 生成对象
        img_code = cap.generate(code)  # 生成图形验证码图片
        # 3.保存验证码
        r = redis.Redis(host='localhost',port=6379,password=123456,db=0)
        r.set(uuid,code,ex=120)
        r.close()
#         返回图形验证码
        return HttpResponse(img_code,content_type='img/png')

class CheckImgCode(APIView):
    def get(self,request):
        # 1.提取GET参数中的uuid和验证码
        uuid = request.query_params.get('imageCodeID')
        img_code = request.query_params.get('imageCode')
#         2.duquredis数据库中的验证码
        r = redis.Redis(host='localhost',password='123456',port=6379,db=0)
        r_code =r.get(uuid)
        if not r_code:
            return Response({'code':204,'msg':'验证码过期'})
        if img_code.lower()==r_code.decode().lower():
            return Response({'code':200,'msg':'ok'})
        else:
            return Response({'code':404,'msg':'验证码错误'})

from .models import User
class Register(APIView):
    def post(self,request):
        # 1.获取前端提交的数据
        username = request.data.get('userName')
        pwd = request.data.get('pwd')
        mobile = request.data.get('mobile')
        aggree = request.data.get('aggree')
        # 2.判断数据是否齐全
        if not all([username,pwd,mobile]):
            return Response({'code':204,'msg':'注册消息不完整'})
        # 3.判断是否同意协议
        if not aggree:
            return Response({'code':204,'msg':'未同意用户协议'})
        # 4.往数据库中保存数据 create_user是AbstractUser提供的方法
        User.objects.create_user(username=username,password=pwd,mobile=mobile)
        return Response({'code':'200','msg':'注册成功'})

import jwt,datetime
from dami import settings
# 生成jwt token
def generate_jwt_token(user):
#     要加密的数据 字典
    payload = {
        'id':user.id,
        'username': user.username,
        'mobile':user.mobile,
        # 'exp': datetime.datetime.now() + datetime.timedelta(seconds=300)
    }
# 进行加密，生成jwt token
    token = jwt.encode(payload=payload,key=settings.SECRET_KEY,algorithm='HS256')

# 返回token
    return token


class Login(APIView):
    def post(self,request):
        # 1.获取用户名和密码
        username = request.data.get('user')
        pwd = request.data.get('pwd')
#         2。读取数据库中的用户信息
        try:
#             3.判断用户是否存在
            from django.db.models import Q
            user = User.objects.get(Q(username=username)|Q(mobile=username))
        except Exception as e:
            print(e)
            return Response({'code':204,'msg':'用户不存在！'})
#         判断密码是否正确
        if not user.check_password(pwd):
            return Response({'code':204,'msg':'用户名或者密码不正确'})
#         密码正确
#         生成用户jwt token
        token=generate_jwt_token(user)
        return Response({
            'code':200,
            'msg':'用户%s登陆成功' % user.username,
            'token':token, # 添加token字段
            'user':{
                "usrName":user.username,
                'uid':user.id
            }
        })



class UserCenter(APIView):
    # 用户信息更新
    def put(self,request):
        # 1.判断用户是否登录
        try:
            user_info = request.user_info
            user = User.objects.get(id=user_info.get('id'))
        except Exception as e:
            return Response({'code': 204, 'msg': '用户不存在或未登录!'})
        # 2.获取前端提交的数据
        phone = request.data.get('phone')
        addrs_list = request.data.get('addrs')
        # 3.修改用户的手机号
        if not re.findall(r'^1[3-9]\d{9}$',phone):
            return Response({'code':204,'msg':'手机号不正确'})
        user.mobile = phone
        user.save()
        # 4.修改地址 循环 一个一个去改
        for i in addrs_list:
            Addr.objects.filter(id=i.get('id')).update(
                receiver =i.get('receiver'),
                receiver_mobile = i.get('receiver_mobile'),
                receiver_addr = i.get('receiver_addr'),
                is_default = i.get("is_default")
            )
        return Response({'msg':'修改信息成功','code':200})

    # 获取用户信息
    def get(self,request):
        # 1.判断用户是否登录
        try:
            user_info = request.user_info
            user = User.objects.get(id=user_info.get('id'))
        except Exception as e:
            return Response({'code':204,'msg':'用户不存在或未登录!'})
        # 2.返回前端需要的数据
        # addrs_list = []
        # 查询用户的地址信息
        addrs_data = user.addr_set.all()
        ser = Addrser(addrs_data,many=True)
        # for i in addrs_data:
        #     addrs_list.append({
        #         'id':i.id,
        #         'receiver':i.receiver,
        #         'receive_mobile':i.receive_mobile,
        #         'receive_addr':i.receive_addr,
        #         'is_default':i.is_default
        #     })
        return Response({
            'code':200,
            'msg':'获取用户信息成功',
            'userInfo':{
                'username':user.username,
                'phone':user.mobile,
                'addrs':ser.data
            }
        })

# 添加用户收货地址
class UserAddr(APIView):
    def post(self,request):
        # 1.判断用户是否登录
        try:
            user_info = request.user_info
            user = User.objects.get(id=user_info.get('id'))
        except Exception as e:
            return Response({'code':204,'msg':'用户不存在或未登录!'})
        # 2.获取前端提交的数据
        receiver = request.data.get('receiver')
        receiver_mobile = request.data.get('receiver_mobile')
        receiver_addr = request.data.get('receiver_addr')
        is_default = request.data.get('is_default')
        # 3.判断数据是否齐全,手机号是否符合要求
        if not all([receiver_addr,receiver_mobile,receiver]):
            return Response({'msg':'信息不全','code':200})
        if not re.findall(r'^1[3-9]\d{9}$',receiver_mobile):
            return Response({'msg':'手机不正确','code':204})
        # 4.默认收货地址处理：只能有一个
        if is_default:
            # 查看该用户是否有默认地址
            default_addr = Addr.objects.filter(user=user,is_default=True)
            default_addr.update(is_default=False)

        # 5.添加新地址
        new_addr = Addr.objects.create(
            receiver=receiver,
            receiver_mobile=receiver_mobile,
            receiver_addr=receiver_addr,
            is_default=is_default,
            user=user
        )
        ser = Addrser(new_addr)
        return Response({'msg':'地址添加成功','code':200,'addrs':ser.data})
    # 删除地址
    def delete(self,request):
        # 1.判断用户是否登录
        try:
            user_info = request.user_info
            user = User.objects.get(id=user_info.get('id'))
        except Exception as e:
            return Response({'code':204,'msg':'用户不存在或未登录!'})
        addr_id = request.data.get('addr_id')
        Addr.objects.filter(id=addr_id).delete()
        return Response({'msg':'删除成功','code':200})



# 修改密码
class UpadatePass(APIView):
    def put(self,request):
        # 1.判断用户是否登录
        try:
            user_info = request.user_info
            user = User.objects.get(id=user_info.get('id'))
        except Exception as e:
            return Response({'code':204,'msg':'用户不存在或未登录!'})
        # 2.获取前端提交的数据
        originPw = request.data.get('originPw')
        newPw = request.data.get('newPw')
        confirmNewPw = request.data.get('confirmNewPw')
        # 3.判断原始密码是否正确
        if not user.check_password(originPw):
            return Response({'msg':'密码错误','code':204})
        # 4.判断新密码和原密码是否一样
        if originPw == newPw:
            return Response({'msg': '密码没有修改', 'code': 204})
        # 5.新密码两次密码不一致
        if newPw != confirmNewPw:
            return Response({'msg': '两次密码不一致', 'code': 204})
        # 6.保存新密码
        user.set_password(newPw)
        user.save()
        return Response({'msg': '修改密码成功', 'code': 200})